 <!--
* description: 索赔申请单规则设置页面
* author: wangjuan
* createdDate: 2020-11-17
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-table-cols="tableCols"
      :dynamic-api-config="apiConfig"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-show-more-btn="true"
      :dynamic-is-init-table="true"
    />

    <edit
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible="editPopupsVisible"
      :popups-state="editPopupsState"
      :dynamic-api-style="'restful'"
      @close="close"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import Vue from 'vue'
import { vehiclePdiPriceInquirys } from '@/api/se/vehiclePdiPriceInquiry'
// import { exportExcel } from '@/utils/getTimeString.js'

export default {
  name: 'ClaimApplicationFormRuleSetting',

  components: {
    OneTableTemplate,
    Edit: () => import('./edit')
  },

  // 组件混入对象：{data[listQuery] methods[queryTable]}
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      // 网格查询API配置对象
      apiConfig: vehiclePdiPriceInquirys.queryPre,
      editRowData: {},
      selectData: {},
      editPopupsVisible: false,
      titleName: '区域审核',
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          size: 'small',
          name: 'add',
          clickEvent: () => this.add(),
          text: this.$t('sys.button.add'),
          position: 'right' // 新增
        },
        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          name: 'importTemplate',
          position: 'upload',
          clickEvent: () => this.handFileListChange(),
          text: '导入'
        },
        {
          compKey: 'btnKey3',
          type: 'text',
          size: 'small',
          name: '',
          position: 'upload',
          click: (event) => {
            this.templateDownload()
          }
        },
        {
          compKey: 'btnKey3',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey4',
          type: '',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        }
      ],
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '授权内容说明：',
              codeField: 'remark',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '效验类型：',
              codeField: 'preType',
              component: () => import('@/components/org/commonSelect'),
              customObj: {
                api: vehiclePdiPriceInquirys.queryType
              },
              type: 'dropdownList',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '效验(配件编码/工时代码)：',
              codeField: 'preCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '效验(配件名称/维修内容)：',
              codeField: 'preName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            }
          ],
      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'subsidyId',
              label: '主键ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'controlBtn',
              label: '操作',
              width: 100,
              fixed: true,
              isComponent: true,
              comps: [
                {
                  compKey: 'propKey1',
                  labelName: '修改',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: (index) => this.edit(index)
                },
                {
                  compKey: 'propKey2',
                  labelName: '删除',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: (index) => this.delete(index)
                }
              ]
            },
            {
              prop: 'remark',
              label: '授权内容说明'
            },
            {
              prop: 'preType',
              label: '效验类型'
            },
            {
              prop: 'preCode',
              label: '效验（配件编码/工时代码）'
            },
            {
              prop: 'preName',
              label: '效验（配件名称/维修内容）'
            },
            {
              prop: 'partSum',
              label: '最低效验值'
            }
          ],

      // 表单数据
      formField: this.$utils.getFormField(
        this,
        {
          remark: '', // 授权内容说明
          preType: '', // 效验类型
          preCode: '', // 工效验(配件编码/工时代码)
          preName: '' // 效验(配件名称/维修内容)
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      )
    }
  },

  mounted() {
    // 列表查询
    this.queryTable(1)
  },

  methods: {
    edit(index) {
      this.editPopupsState = 'edit'
      this.editPopupsVisible = true
      this.editRowData = this.$refs['multipleTable'].list[index]
    },
    close() {
      this.editPopupsVisible = false
      this.queryTable(1)
    },
    // 删除
    delete(index) {
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: {
          APIUrl: '/mp/e3sh/aftersale/preauthorizationservice/DleIsEnable.do'
        },
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: this.$refs['multipleTable'].list[index]
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then((response) => {
        if (response.result === '1') {
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 1000
          })

          this.queryTable(1)
        } else {
          // 保存失败
          this.$message({
            message: '删除失败:' + response.msg,
            type: 'warn',
            uration: 1000
          })
        }
      })
      console.log(this.$refs['multipleTable'].list[index], 8888)
    },
    // 模板下载
    templateDownload() {
      const fileName = this.$utils.fileNameWithTime('索赔申请单规则设置.xlsx')
      this.$requestAPI({
        apiUrl: '/mp/e3sh/aftersale/preauthorizationservice/Load.do',
        variables: { dataType: 'excel' }
      })
        .then((res) => {
          this.$utils.downloadFile(res, fileName)
        })
        .catch((err) => {
          console.log(err)
        })
    },
    handFileListChange(file, fileList) {
      if (this.beforeAvatarUpload(file)) {
        this.handleChange(file)
      }
    },
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: '文件大小不能超过50M',
          type: 'warning'
        })
        return false
      }
      const fileType = file.name.substr(file.name.lastIndexOf('.') + 1)
      if (fileType != 'xls' && fileType != 'xlsx') {
        this.$message({
          message: '只能导入后缀为xls,xlsx的文件！',
          type: 'warning'
        })
        return false
      }
      return true
    },
    handleChange(param) {
      const loading = this.$loading({
        lock: true,
        text: '导入中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const that = this
      const url = '/mp/e3sh/aftersale/preauthorizationservice/importPre.do'
      that
        .$requestUpload(url, param)
        .then((response) => {
          loading.close()
          if (response.result === '1') {
            this.$message({
              message: '导入成功',
              type: 'success'
            })
            that.queryTable()
          } else {
            this.$message({
              message: response.msg,
              type: 'warning'
            })
          }
        })
    }
  }
}
</script>
